package main

import (
	"bytes"
	"encoding/gob"
	"log"
	"time"
)

type Block struct {
	Timestamp	int64
	Data	[]byte
	PrevBlockHash	[]byte
	Hash	[]byte
	Nonce	int
}

// 将Block序列化为一个字节数组
func (block *Block) Serialize() []byte{
	var result bytes.Buffer
	encoder := gob.NewEncoder(&result)
	err := encoder.Encode(block)
	if err!=nil{
		log.Panic(err)
	}
	return result.Bytes()
}
// 将字节数组反序列化为一个Block
func DeserializeBlock(d []byte) *Block{
	var block Block
	decoder := gob.NewDecoder(bytes.NewReader(d))
	err := decoder.Decode(&block)
	if err!=nil{
		log.Panic(err)
	}
	return &block
}

func NewBlock(data string,prevBlockHash []byte) *Block {
	block := &Block{
		Timestamp:time.Now().Unix(),
		Data:[]byte(data),
		PrevBlockHash:prevBlockHash,
		Hash:[]byte{},
		Nonce:0}
	pow := NewProofOfWork(block)
	nonce,hash := pow.Run()
	block.Hash = hash[:]
	block.Nonce = nonce
	return block
}

func NewGenesisBlock() *Block {
	return NewBlock("Genesis Block", []byte{})
}
